package cn.itcast.realm;

import cn.itcast.domain.system.Module;
import cn.itcast.domain.system.User;
import cn.itcast.service.system.ModuleService;
import cn.itcast.service.system.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class SaasRealm extends AuthorizingRealm {


    @Autowired
    private UserService userService;
    @Autowired
    private ModuleService moduleService;

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("---------------------------认证doGetAuthenticationInfo------------------------------");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String email = token.getUsername();
        String password_page = new String(token.getPassword());
//
        User user = userService.findByEmail(email);
        if(user!=null){
            String password_db = user.getPassword();
            if(password_page.equals(password_db)){
//                Object principal 主角（当前登录人）, Object credentials 加密后的密码, String realmName 当前类名
                return new SimpleAuthenticationInfo(user,password_page,getName());
            }

        }

//        这里一旦return null那么subject.login(token)就会出异常
        return null;   //如果user为空或密码不相等都会return null
    }

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("+++++++++++++++++++++++++++++++授权AuthorizationInfo++++++++++++++++++++++++++++++++++");
//        告诉shiro框架当前登录人有哪些权限
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

       /* info.addStringPermission("企业管理");
        info.addStringPermission("用户管理");*/

//        查询当前登录人有哪些权限
//        User user = (User) SecurityUtils.getSubject().getPrincipal();
        User user = (User) principalCollection.getPrimaryPrincipal();

        List<Module> moduleList = moduleService.findModuleListByUser(user);

        for (Module module : moduleList) {
            info.addStringPermission(module.getName());
        }

        info.addRole("销售专责");
        info.addRole("总经理");
        return info;
    }


}
